package com.ck567.netty.chatroom.server.handler

import com.ck567.netty.chatroom.message.GroupQuitRequestMessage
import com.ck567.netty.chatroom.message.GroupQuitResponseMessage
import com.ck567.netty.chatroom.server.session.GroupSessionFactory
import com.ck567.netty.chatroom.util.logger
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

@ChannelHandler.Sharable
class GroupQuitMessageHandler : SimpleChannelInboundHandler<GroupQuitRequestMessage>(){
    override fun channelRead0(ctx: ChannelHandlerContext, msg: GroupQuitRequestMessage) {
        logger.info("================")
        logger.info("退出群组：$msg")
        val group = GroupSessionFactory.getSession().removeMember(msg.groupName, msg.from)
        if(group==null){
            ctx.writeAndFlush(GroupQuitResponseMessage(false,"该群组不存在！"))
        }else{
            ctx.writeAndFlush(GroupQuitResponseMessage(true,"退出群组成功！"))
            if((group.members == null) || (group.members?.size == 0)){
                GroupSessionFactory.getSession().removeGroup(msg.groupName)
                ctx.writeAndFlush(GroupQuitResponseMessage(true,"该群组已解散！"))
            }
        }
    }
    companion object {
        private val logger = logger<GroupQuitMessageHandler>()
    }
}